﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HookINCS;
using System.Runtime.InteropServices;
namespace RkErp
{
    public partial class FrmMain : Form
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left, Top, Right, Bottom;
        }
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);

        bool bOpen = true;
        public FrmMain()
        {
            InitializeComponent();
        }
        MouseHook mouseHook;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            mouseHook = new MouseHook();
            mouseHook.SetHook();//添加钩子
            //鼠标移动，点击
            mouseHook.MouseMove += new MouseEventHandler(mouseHook_MouseMove);
            mouseHook.Click += new MouseEventHandler(mouseHook_Click);
        }
        private void mouseHook_MouseMove(object sender, MouseEventArgs e)
        {
            this.Text = string.Format("pos:{0},{1}", e.Location.X, e.Location.Y);
        }
        private void mouseHook_Click(object sender, MouseEventArgs e)
        {
            IntPtr hWnd = GetNetSetHwnd();//获取 局域网设置 按钮 句柄
            if (hWnd.ToInt32() == 0)
            {
                return;
            }
            RECT rect = new RECT();
            GetWindowRect(hWnd,out rect);
            int x = e.Location.X;
            int y = e.Location.Y;
            if (rect.Left < x && x < rect.Right && 
                rect.Top < y && y < rect.Bottom)
            {
                bOpen = !bOpen;
                this.Text = bOpen ? "开启" : "关闭";
            }
        }
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            mouseHook.UnLock();//卸载钩子
        }
        private IntPtr GetNetSetHwnd()
        {
            IntPtr hWnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "Internet 选项");
            if (hWnd.ToInt32() != 0)
            {
                hWnd = FindWindowEx(hWnd, IntPtr.Zero, null, "连接");
                if (hWnd.ToInt32() != 0)
                {
                    hWnd = FindWindowEx(hWnd, IntPtr.Zero, null, "局域网设置(&L)");
                }
            }
            return hWnd;
        }
    }
}
